// 原生震动功能封装
class NativeVibrate {
  // 测试震动功能
  testVibrate() {
    console.log("开始测试震动功能...");

    // 方法1: uni.vibrate
    this.testUniVibrate();

    // 方法2: uni.vibrateLong
    setTimeout(() => {
      this.testUniVibrateLong();
    }, 2000);

    // 方法3: 原生Android震动
    setTimeout(() => {
      this.testNativeVibrate();
    }, 4000);
  }

  // 测试 uni.vibrate
  testUniVibrate() {
    console.log("测试 uni.vibrate...");
    uni.vibrate({
      success: () => {
        console.log("✅ uni.vibrate 成功");
        uni.showToast({
          title: "uni.vibrate 成功",
          icon: "none",
        });
      },
      fail: (err) => {
        console.error("❌ uni.vibrate 失败:", err);
        uni.showToast({
          title: "uni.vibrate 失败",
          icon: "none",
        });
      },
    });
  }

  // 测试 uni.vibrateLong
  testUniVibrateLong() {
    console.log("测试 uni.vibrateLong...");
    try {
      uni.vibrateLong({
        success: () => {
          console.log("✅ uni.vibrateLong 成功");
          uni.showToast({
            title: "uni.vibrateLong 成功",
            icon: "none",
          });
        },
        fail: (err) => {
          console.error("❌ uni.vibrateLong 失败:", err);
          uni.showToast({
            title: "uni.vibrateLong 失败",
            icon: "none",
          });
        },
      });
    } catch (error) {
      console.error("uni.vibrateLong 不支持:", error);
      uni.showToast({
        title: "uni.vibrateLong 不支持",
        icon: "none",
      });
    }
  }

  // 测试原生Android震动
  testNativeVibrate() {
    // #ifdef APP-PLUS
    try {
      console.log("测试原生Android震动...");

      const main = plus.android.runtimeMainActivity();
      const Context = plus.android.importClass("android.content.Context");
      const Vibrator = plus.android.importClass("android.os.Vibrator");

      // 获取震动服务
      const vibrator = main.getSystemService(Context.VIBRATOR_SERVICE);

      // 检查是否支持震动
      if (vibrator.hasVibrator()) {
        console.log("设备支持震动");

        // Android API 26+ 使用 VibrationEffect
        if (
          plus.android.importClass("android.os.Build$VERSION").SDK_INT >= 26
        ) {
          const VibrationEffect = plus.android.importClass(
            "android.os.VibrationEffect"
          );
          const effect = VibrationEffect.createOneShot(
            1000,
            VibrationEffect.DEFAULT_AMPLITUDE
          );
          vibrator.vibrate(effect);
        } else {
          // 旧版本Android
          vibrator.vibrate(1000);
        }

        console.log("✅ 原生震动执行成功");
        uni.showToast({
          title: "原生震动成功",
          icon: "none",
        });
      } else {
        console.log("❌ 设备不支持震动");
        uni.showToast({
          title: "设备不支持震动",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("❌ 原生震动失败:", error);
      uni.showToast({
        title: "原生震动失败: " + error.message,
        icon: "none",
      });
    }
    // #endif

    // #ifndef APP-PLUS
    console.log("非APP环境，无法测试原生震动");
    uni.showToast({
      title: "非APP环境",
      icon: "none",
    });
    // #endif
  }

  // 强力震动 - 多种方法组合
  powerVibrate() {
    console.log("执行强力震动...");

    // 方法1: uni.vibrate
    uni.vibrate({
      success: () => console.log("uni.vibrate 执行"),
      fail: (err) => console.error("uni.vibrate 失败:", err),
    });

    // 方法2: 原生震动
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const Context = plus.android.importClass("android.content.Context");
      const Vibrator = plus.android.importClass("android.os.Vibrator");

      const vibrator = main.getSystemService(Context.VIBRATOR_SERVICE);

      if (vibrator.hasVibrator()) {
        // 震动模式：震动500ms，停止300ms，重复5次
        const pattern = plus.android.newObject(
          "long[]",
          [0, 500, 300, 500, 300, 500, 300, 500, 300, 500]
        );

        if (
          plus.android.importClass("android.os.Build$VERSION").SDK_INT >= 26
        ) {
          const VibrationEffect = plus.android.importClass(
            "android.os.VibrationEffect"
          );
          const effect = VibrationEffect.createWaveform(pattern, -1);
          vibrator.vibrate(effect);
        } else {
          vibrator.vibrate(pattern, -1);
        }

        console.log("原生震动模式执行");
      }
    } catch (error) {
      console.error("原生震动失败:", error);
    }
    // #endif
  }

  // 连续震动
  continuousVibrate(times = 5, interval = 800) {
    let count = 0;

    const doVibrate = () => {
      if (count < times) {
        console.log(`执行第 ${count + 1} 次震动`);

        // uni-app震动
        uni.vibrate({
          success: () => console.log(`第 ${count + 1} 次 uni.vibrate 成功`),
          fail: (err) =>
            console.error(`第 ${count + 1} 次 uni.vibrate 失败:`, err),
        });

        // 原生震动
        // #ifdef APP-PLUS
        try {
          const main = plus.android.runtimeMainActivity();
          const Context = plus.android.importClass("android.content.Context");
          const Vibrator = plus.android.importClass("android.os.Vibrator");

          const vibrator = main.getSystemService(Context.VIBRATOR_SERVICE);
          if (vibrator.hasVibrator()) {
            if (
              plus.android.importClass("android.os.Build$VERSION").SDK_INT >= 26
            ) {
              const VibrationEffect = plus.android.importClass(
                "android.os.VibrationEffect"
              );
              const effect = VibrationEffect.createOneShot(
                400,
                VibrationEffect.DEFAULT_AMPLITUDE
              );
              vibrator.vibrate(effect);
            } else {
              vibrator.vibrate(400);
            }
          }
        } catch (error) {
          console.error("原生震动失败:", error);
        }
        // #endif

        count++;
        setTimeout(doVibrate, interval);
      } else {
        console.log("连续震动完成");
      }
    };

    doVibrate();
  }

  // 检查震动权限
  checkVibratePermission() {
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const Context = plus.android.importClass("android.content.Context");
      const PackageManager = plus.android.importClass(
        "android.content.pm.PackageManager"
      );

      const permission = "android.permission.VIBRATE";
      const result = main.checkSelfPermission(permission);

      if (result === PackageManager.PERMISSION_GRANTED) {
        console.log("✅ 震动权限已授予");
        return true;
      } else {
        console.log("❌ 震动权限未授予");
        return false;
      }
    } catch (error) {
      console.error("检查震动权限失败:", error);
      return false;
    }
    // #endif

    return true; // 非APP环境默认返回true
  }

  // 请求震动权限
  requestVibratePermission() {
    // #ifdef APP-PLUS
    try {
      plus.android.requestPermissions(
        ["android.permission.VIBRATE"],
        (result) => {
          console.log("震动权限请求结果:", result);
          if (result.granted && result.granted.length > 0) {
            uni.showToast({
              title: "震动权限已获取",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: "震动权限被拒绝",
              icon: "none",
            });
          }
        },
        (error) => {
          console.error("请求震动权限失败:", error);
          uni.showToast({
            title: "权限请求失败",
            icon: "none",
          });
        }
      );
    } catch (error) {
      console.error("请求震动权限异常:", error);
    }
    // #endif
  }
}

export default new NativeVibrate();
